<?php
/*
 * @Description: 支付宝初始化类
 * @Author: QianLong
 * @Date: 2019-09-27 16:34:02
 * @LastEditors    : QianLong
 * @LastEditTime   : 2022-05-28 17:04:58
 */

namespace app\common\service\alipay;

use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Config;
use app\common\RedisCache;
use app\lib\exception\ApiException;

class Options
{
    protected $infoData;
    public function __construct()
    {
        $this->infoData = (new RedisCache())::getSysPaySetting('alipay');
        if (empty($this->infoData)) {
            throw new ApiException("支付宝配置为空");
        }
        Factory::setOptions($this->getOptions());
    }

    public function getOptions()
    {
        $options = new Config();
        $options->protocol = 'https';
        $options->gatewayHost = 'openapi.alipay.com';
        $options->signType = 'RSA2';
        $options->appId = $this->infoData['app_id'];
        // 为避免私钥随源码泄露，推荐从文件中读取私钥字符串而不是写入源码中
        $options->merchantPrivateKey = $this->infoData['application_private_key'];
        if ($this->infoData['type'] == 1) {
            $options->alipayCertPath = root_path().'/crt/'.$this->infoData['alipay_cert_path'];
            $options->alipayRootCertPath = root_path().'/crt/'.$this->infoData['alipay_root_cert_path'];
            $options->merchantCertPath = root_path().'/crt/'.$this->infoData['application_cert_path'];
        } else {
            $options->alipayPublicKey = $this->infoData['alipay_public_key'];
        }
        //可设置异步通知接收服务地址（可选）
        if (!empty($this->infoData['notify_url'])) {
            $options->notifyUrl = $this->infoData['notify_url'];
        }
        //可设置AES密钥，调用AES加解密相关接口时需要（可选）
        // $options->encryptKey = "<-- 请填写您的AES密钥，例如：aa4BtZ4tspm2wnXLb1ThQA== -->";
        return $options;
    }
}
